<template>
  <div>
    <a-row class="container">
      <a-row :span="20" style="margin: 10px 25px 20px 5px">
        <a-spin :spinning="Tree_spin_status" tip="Loading...">
          <a-tree-select
            style="width: 100%"
            :value="value"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :placeholder="orgName"
            allow-clear
            tree-default-expand-all
            @change="onChange"
          >
            <a-tree-select-node
              :key="item._id"
              :value="`${item._id}#`"
              :title="item._id"
              v-for="item in treeData"
            >
              <a-tree-select-node
                :key="mName"
                :value="`${mName}:${item._id}`"
                :title="mName"
                v-for="mName in item.majors"
              >
              </a-tree-select-node>
            </a-tree-select-node>
          </a-tree-select>
        </a-spin>
      </a-row>
      <batchAddCourse :visible.sync="bulkImport_visible"></batchAddCourse>
      <a-row class="btn-area">
        <div  class="input">
          <a-input-search
            placeholder="班级编号/名称"
            enter-button
            @search="onSearch"
          />
        </div>
        <a-col :span="10"></a-col>
        <a-col :span="9" class="btn">
          <a-space>
            <a-button type="primary" @click="bulkImport_visible = true"
              >批量添加课程</a-button
            >
            <a-button type="primary" @click="addCourseVisible = true"
              >添加课程</a-button
            >
            <a-button type="primary" @click="showDeleteConfirms()"
              >批量删除</a-button
            >
          </a-space>
        </a-col>
      </a-row>
      <a-row :span="20">
        <a-tabs :active-key="activeIndex" @change="callback">
          <a-tab-pane key="1" tab="简介" force-render>
            <a-spin :spinning="spin_status" tip="Loading...">
              <course-dashboard
                class="class-dashboard"
                :courseProp="courseList"
                :collegeName="value"
              ></course-dashboard>
            </a-spin>
          </a-tab-pane>

          <a-tab-pane key="2" tab="课程">
            <a-spin :spinning="spin_status" tip="Loading...">
              <course-table
                class="class-table"
                :courses="courseList2"
                :colleges="colleges"
                :orgName="orgName"
                :years="years"
                @updateTree="getTreeData"
                ref="courseTable"
              ></course-table>
            </a-spin>
          </a-tab-pane>
        </a-tabs>
      </a-row>
    </a-row>

    <a-modal
      v-model="addCourseVisible"
      title="添加课程"
      @ok="submitAddCourse"
      :maskClosable="false"
    >
      <a-form-model
        :model="courseForm"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="学校">
          <p>{{ orgName }}</p>
        </a-form-model-item>
        <a-form-model-item label="课程编号">
          <a-input
            placeholder="请输入课程编号"
            v-model="courseForm.course_id"
          ></a-input>
        </a-form-model-item>
        <a-form-model-item label="课程名称">
          <a-input
            placeholder="请输入课程名称"
            v-model="courseForm.name"
          ></a-input>
        </a-form-model-item>
        <a-form-model-item label="学院">
          <a-select v-model="subOrg_name">
            <a-select-option
              v-for="item in colleges"
              :key="item._id"
              :value="item.subOrgName"
            >
              {{ item.subOrgName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="专业">
          <a-select v-model="courseForm.major_name">
            <a-select-option
              v-for="item in major_names"
              :key="item._id"
              :value="item.majorName"
            >
              {{ item.majorName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="学分">
          <a-select v-model="courseForm.credit">
            <a-select-option v-for="number in 5" :key="number">
              {{ number }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="开课学期">
          <a-select v-model="courseForm.semester">
            <a-select-option v-for="number in 8" :key="number">
              {{ number }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="周学时">
          <a-select v-model="courseForm.weekly_hrs">
            <a-select-option v-for="number in 6" :key="number">
              {{ number }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!--<a-form-model-item label="实践或实验">
        </a-form-model-item>-->
        <a-form-model-item label="考试方式">
          <a-select v-model="courseForm.evaluation">
            <a-select-option v-for="i in evaluation" :key="i">
              {{ i }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="总学时">
          <a-input
            placeholder="请输入总学时"
            v-model="courseForm.total_study_hours"
          ></a-input>
        </a-form-model-item>
        <a-form-model-item label="课程类型">
          <a-select v-model="courseForm.course_type">
            <a-select-option v-for="i in course_type" :key="i">
              {{ i }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="开课年级">
          <a-select v-model="courseForm.grade">
            <a-select-option v-for="i in years" :key="i">
              {{ i }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import batchAddCourse from "./BatchAddCourse.vue";
import courseTable from "./CourseTable";
import courseDashboard from "./CourseTree";
import axiosInstance from "@/utils/axios";
import { mapState } from "vuex";
import moment from "moment";
import axios from "@/utils/axios";

export default {
  components: { courseTable, courseDashboard, batchAddCourse },
  data() {
    return {
      // 加载树
      Tree_spin_status: false,

      selectMajor: "",
      refresh: 1,
      addCourseVisible: false,
      experiment_or_traning: ["实践", "实验"],
      evaluation: ["考试", "考察"],
      course_type: ["专业方向课", "学院基础课", "公共基础课"],
      changeDeleteStatus: "false",
      subOrg_name: "",
      colleges: [],
      major_names: [],
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      bulkImport_visible: false,
      value: undefined,
      courseList: [],
      courseList2: [],
      courseList3: [],
      treeData: [],
      collogeName: "",
      activeIndex: "1",
      flag: "",
      collegeList: [],
      majorList: [],
      collegeNumber: 0,
      majorNumber: 0,
      courseNumber: 0,
      pieArr: [],
      // 添加课程表单
      courseForm: {
        org_name: "",
        course_id: "",
        name: "",
        subOrg_name: "",
        major_name: "",
        credit: "",
        semester: "",
        weekly_hrs: "",
        evaluation: "",
        total_study_hours: "",
        course_type: "",
        grade: "",
      },
    };
  },
  computed: {
    ...mapState({
      // Tree_spin_status: (state) => state.admin.Tree_spin_status,
      spin_status: (state) => state.admin.spin_status,
      uid: (state) => state.public.uid,
      oid: (state) => state.public.oid,
      orgName: (state) => state.public.orgName,
    }),
    years() {
      let year = moment().year();
      return [year - 3, year - 2, year - 1, year, year + 1, year + 2, year + 3];
    },
  },
  mounted() {
    this.getCoursesFromCondition({ org_name: this.orgName }, 1);
    this.getTreeData();
    this.getSubOrgsName();
  },
  watch: {
    refresh(val) {
      this.getCoursesFromCondition();
    },
    subOrg_name(val) {
      // 根据学院找到专业赋值
      this.courseForm.subOrg_name = val;
      this.getmajors(val);
    },
  },
  methods: {
    //搜索
    onSearch(val) {
      console.log(this.courseList);
      this.courseList2 = this.courseList3;
      if (val == ""){
        this.courseList = this.courseList3;
      }
      else{      
        this.courseList2 =  this.courseList2.filter((course) => {
          return course.name.includes(val);
        });
        this.courseList = this.courseList2;
      }
    },
    //添加单个课程
    async submitAddCourse() {
      try {
        this.courseForm.org_name = this.orgName;
        const url = `/pc/v1/courses`;
        let requestBody = this.courseForm;
        const {data} = await axiosInstance.post(url, requestBody);
        console.log("data");
        console.log(data);
        requestBody = { ...requestBody, _id: data.newCourse._id };
        console.log("request");
        console.log(requestBody);
        this.$message.info("添加成功");
        // 刷新数据
        this.getTreeData();
        if (this.selectMajor == requestBody.major_name) {
          let newCourse = Object.assign({}, requestBody);
          this.courseList2.push(newCourse);
        }
        let newCourse = Object.assign({}, requestBody);
        this.courseList.push(newCourse);
        this.addCourseVisible = false;
      } catch (err) {
        this.$message.error("添加失败");
        this.addCourseVisible = false;
        console.log(err);
      }
    },

    async getSubOrgsName() {
      // 获取学院名
      const orgId = this.oid;
      const url = "/pc/v1/organizations/" + orgId + "/suborgs";
      try {
        const { data } = await axiosInstance.get(url);
        console.log("学院");
        console.log(data.subOrgs);
        this.colleges = data.subOrgs;
      } catch (err) {
        console.log(err);
      }
    },
    async getmajors(queryString) {
      // 按学院获取专业
      this.courseForm.major_name = "";
      const url =
        "/pc/v1/organizations/" + this.orgName + "/suborgs/" + queryString;
      try {
        const { data } = await axiosInstance.get(url);
        console.log(data.majors);
        this.major_names = data.majors;
      } catch (err) {
        console.log(err);
      }
    },

    //批量删除课程
    showDeleteConfirms() {
      if (!this.$refs.courseTable || !this.$refs.courseTable.selectedCourses) {
        this.$message.error("请点击具体专业再删除课程！");
        return;
      }
      let deleteList = this.$refs.courseTable.selectedCourses;
      var that = this;
      deleteList.length == 0
        ? this.$message.info("请选中删除项")
        : this.$confirm({
            title: "确认删除吗",
            content: "数据删除后不可恢复",
            okText: "确定",
            okType: "danger",
            cancelText: "取消",
            async onOk() {
              console.log(deleteList);
              //post deleteList
              let requestbody = { courses_id: deleteList };
              const url = "/pc/v1/courses/batchDeleteCourses";
              try {
                await axiosInstance.post(url, requestbody);
                that.$message.info("删除成功！");
                that.getTreeData();
                that.courseList2 = that.courseList2.filter((n) => {
                  return !deleteList.includes(n._id);
                });
              } catch (err) {
                console.log(err);
                that.$message.error("删除失败，请重试！");
              }
            },
            onCancel() {
              // console.log("Cancel");
            },
          });
    },

    // async
    async getTreeData() {
      let queryString = this.orgName;
      const url = "/pc/v1/courses/courseTree?org_name=" + queryString;
      // console.log(url);
      this.Tree_spin_status = true;
      var response;
      try {
        response = await axios.get(url);
        this.Tree_spin_status = false;
      } catch (err) {
        this.$message.error("请求数据失败，请检查网络连接！");
        this.Tree_spin_status = false;
        return;
      }
      this.treeData = response.data.data;
      this.courseNumber = response.data.totalCourseNumber;
      this.collegeNumber = this.treeData.length;

      let mNumber = 0;
      let tempArr = [];
      this.treeData.forEach((item) => {
        let pieObj = {};
        pieObj.name = item._id;
        item.majors.forEach(() => {
          mNumber++;
        });
        pieObj.value = mNumber;
        tempArr.push(pieObj);
      });
      this.pieArr = tempArr;
      this.majorNumber = mNumber;
      // this.$store
      //   .dispatch("admin/getTreeByURLwithSpin", url)
      //   .then((response) => {
      //     console.log("--------coursesTree--------");
      //     console.log(response);
      //     this.treeData = response.data.data;
      //     this.courseNumber = response.data.totalCourseNumber;
      //     this.collegeNumber = this.treeData.length;

      //     let mNumber = 0;
      //     let tempArr = [];
      //     this.treeData.forEach((item, index) => {
      //       let pieObj = {};
      //       pieObj.name = item._id;
      //       item.majors.forEach(() => {
      //         mNumber++;
      //       });
      //       pieObj.value = mNumber;
      //       tempArr.push(pieObj);
      //     });
      //     this.pieArr = tempArr;
      //     this.majorNumber = mNumber;
      //   })
      //   .catch((error) => {
      //     console.log(error);
      //   });

      // try {
      //   this.$store.dispatch("admin/change_Tree_spin_status", true);
      //   const { data } = await axiosInstance.get(url);
      //   this.$store.dispatch("admin/change_Tree_spin_status", false);
      //   // console.log(data);
      //   this.treeData = data.data;
      //   this.courseNumber = data.totalCourseNumber;
      //   this.collegeNumber = this.treeData.length;

      //   let mNumber = 0;
      //   let tempArr = [];
      //   this.treeData.forEach((item, index) => {
      //     let pieObj = {};
      //     pieObj.name = item._id;
      //     item.majors.forEach(() => {
      //       mNumber++;
      //     });
      //     pieObj.value = mNumber;
      //     tempArr.push(pieObj);
      //   });
      //   this.pieArr = tempArr;
      //   this.majorNumber = mNumber;
      // } catch (err) {
      //   console.log(err);
      // }
    },

    // async
    getCoursesFromCondition(payload, type) {
      let queryString = "";
      Object.keys(payload).forEach((key) => {
        queryString += key + "=" + payload[key] + "&";
      });
      queryString = "?" + queryString.slice(0, -1);
      const url = "/pc/v1/courses" + queryString;

      this.$store
        .dispatch("admin/getTreeByURLwithSpin", url)
        .then((response) => {
          console.log("--------- coursesFromCondition--------");
          console.log(response);
          if (type == 1) {
            this.courseList = response.data.courses;
            // console.log(this.courseList);
          } else if (type == 2) {
            this.courseList2 = response.data.courses;
          }
          this.courseList3 = response.data.courses;
        })
        .catch((error) => {
          console.log(error);
        });

      // console.log(url);
      // try {
      //   this.$store.dispatch("admin/change_spin_status", true);
      //   const { data } = await axiosInstance.get(url);
      //   this.$store.dispatch("admin/change_spin_status", false);
      //   if (type == 1) {
      //     this.courseList = data.courses;
      //     // console.log(this.courseList);
      //   } else if (type == 2) {
      //     this.courseList2 = data.courses;
      //     // console.log(this.courseList2);
      //   }
      // } catch (err) {
      //   console.log(err);
      // }
    },
    async onChange(value, label) {
      // console.log("onchange:  value " + value);
      // console.log("onchange:   label" + label);
      this.flag = value;
      if (this.flag.slice(-1) == "#") {
        let payload = {};
        this.activeIndex = "1";
        let temp = this.flag.slice(0, -1);
        payload = { subOrg_name: temp };
        this.getCoursesFromCondition(payload, 1);
      } else {
        let payload = {};
        this.activeIndex = "2";
        let dataArray = this.flag.split(":");
        payload = { subOrg_name: dataArray[1], major_name: dataArray[0] };
        this.selectMajor = dataArray[0];
        // console.log(payload);
        this.getCoursesFromCondition(payload, 2);

        // console.log("代码出差");
      }
      // console.log(label);
      this.value = label;
    },
    callback() {},
  },
};
</script>

<style scoped>
.class-table {
  padding-left: 20px;
}

.container {
  padding: 10px;
  height: 100%;
}

</style>
